package com.appengine.news.service;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appengine.news.entity.RssFeedEntity;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.labs.taskqueue.TaskOptions;
import com.google.appengine.api.labs.taskqueue.TaskOptions.Builder;

/**
 * Add tasks to run
 * 
 * @author Aliaksandr_Spichakou
 * 
 */
public class UpdateService extends AbstractService{
	/**
	 * 
	 */
	private static final long serialVersionUID = -3170937202929731666L;

	private static final Logger log = Logger.getLogger(UpdateService.class
			.getName());

	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {
		log.entering(UpdateTask.class.getName(), "service");
		final Queue queue = QueueFactory.getQueue(DEFAULT_QUEUE);
		final List<RssFeedEntity> feed2Update0 = getFeed2Update(F_UPDATE_HOUR);
		final List<RssFeedEntity> feed2Update1 = getFeed2Update(F_UPDATE_HALF_HOUR);
		final List<RssFeedEntity> feed2Update2 = getFeed2Update(F_UPDATE_10_MIN);

		final Set<RssFeedEntity> list = new HashSet<RssFeedEntity>();
		list.addAll(feed2Update0);
		list.addAll(feed2Update1);
		list.addAll(feed2Update2);

		final Iterator<RssFeedEntity> iterator = list.iterator();
		while(iterator.hasNext()){
			final RssFeedEntity rssFeedEntity = iterator.next();
			TaskOptions options = Builder.url(UPDATE_RSS_TASK);
			options = options.param(FEED_ID, rssFeedEntity.getId() + "");
			queue.add(options);
		}
		log.exiting(UpdateTask.class.getName(), "service");
	}

	/**
	 * Get feeds to update
	 * 
	 * @param freq
	 * @return
	 */
	private List<RssFeedEntity> getFeed2Update(int freq) {
		log.entering(UpdateTask.class.getName(), "getFeed2Update");
		final GregorianCalendar calendar = new GregorianCalendar();
		if(freq<F_UPDATE_HOUR)
		{
			calendar.roll(Calendar.MINUTE, -freq/60000);
		}
		else
		{
			calendar.roll(Calendar.HOUR, -freq/3600000);
		}
		
		final Date time = calendar.getTime();
		final PersistenceManager pm = getPersistenceManager();
		final Query query = pm.newQuery("select from "
				+ RssFeedEntity.class.getName()
				+ " where lastUpdate < updateDate && updateFreq==" + freq);
		query.declareParameters("java.util.Date updateDate");
		final List<RssFeedEntity> items = (List<RssFeedEntity>) pm.newQuery(
				query).execute(time);
		log.exiting(UpdateTask.class.getName(), "getFeed2Update");
		return items;
	}	
}
